package org.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.chen.common.SignUp;
import org.chen.exception.CustomException;
import org.chen.mapper.SignUpMapper;
import org.chen.result.BaseResponse;
import org.chen.result.CommonResponse;
import org.chen.service.SignUpService;
import org.chen.service_enum.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class SignUpServiceImpl extends ServiceImpl<SignUpMapper, SignUp> implements SignUpService {
    @Autowired
    private SignUpMapper signUpMapper;

    @Override
    public CommonResponse signUp(SignUp signUp) {
        if (signUp == null || signUp.getUserId() == null){
            throw new CustomException(ErrorCode.BAD_REQUEST);
        }
        SignUp usrByUserId = signUpMapper.selectOne(new QueryWrapper<SignUp>().eq("userId", signUp.getUserId()));

        if (usrByUserId == null){
            signUp.setSingUp(1);
            signUp.setIntegralValue(10);
            int insert = signUpMapper.insert(signUp);
            if (insert > 0){
                return CommonResponse.success();
            }
        }else {
            usrByUserId.setLastSignUpDate(signUp.getLastSignUpDate());
            usrByUserId.setSingUp(usrByUserId.getSingUp() + 1);
            usrByUserId.setIntegralValue(usrByUserId.getIntegralValue() + 10);
            int i = signUpMapper.updateById(usrByUserId);
            if (i > 0){
                return CommonResponse.success();
            }
        }
        return CommonResponse.error(ErrorCode.SAVE_FAILED.getCode(), ErrorCode.SAVE_FAILED.getMessage(), ErrorCode.SAVE_FAILED.getMessage());
    }

    @Override
    public BaseResponse<SignUp> getByUserId(String userId) {
        if (userId == null){
            throw new CustomException(ErrorCode.BAD_REQUEST);
        }
        SignUp userId1 = signUpMapper.selectOne(new QueryWrapper<SignUp>().eq("userId", userId));
        return BaseResponse.success(Objects.requireNonNullElseGet(userId1, SignUp::new));
    }
}
